using System.Text.RegularExpressions;

namespace CSharpPro._1103;

public class UserService : IUserService
{
    private readonly List<User> _users = new List<User>();

    public void Run()
    {
        bool isRunning = true;
        Console.WriteLine("=== 用户登录与注册系统 ===");

        while (isRunning)
        {
            Console.WriteLine("\n===== 主菜单 =====");
            Console.WriteLine("1. 登录");
            Console.WriteLine("2. 注册");
            Console.WriteLine("3. 删除用户");
            Console.WriteLine("4. 退出");
            Console.Write("请选择功能（输入数字1-4）：");

            string input = Console.ReadLine()?.Trim();
            if (string.IsNullOrEmpty(input))
            {
                Console.WriteLine("输入不可为空，请重新输入！");
                continue;
            }

            if (!int.TryParse(input, out int choice))
            {
                Console.WriteLine("输入错误，请输入有效数字（1-4）！");
                continue;
            }

            switch (choice)
            {
                case 1:
                    HandleLogin();
                    break;
                case 2:
                    HandleRegister();
                    break;
                case 3:
                    HandleDeleteUser();
                    break;
                case 4:
                    isRunning = false;
                    Console.WriteLine("系统已退出，感谢使用！");
                    break;
                default:
                    Console.WriteLine("输入错误，请选择1-4之间的数字！");
                    break;
            }
        }
    }

    public bool Register(string username, string password)
    {
        // 使用foreach循环验证用户名唯一性
        foreach (var user in _users)
        {
            if (user.Username == username)
            {
                return false;
            }
        }

        _users.Add(new User(username, password));
        return true;
    }

    public bool Login(string username, string password)
    {
        // 使用foreach循环验证登录信息
        foreach (var user in _users)
        {
            if (user.Username == username && user.Password == password)
            {
                return true;
            }
        }

        return false;
    }

    public bool DeleteUser(string username)
    {
        for (int i = 0; i < _users.Count; i++)
        {
            if (_users[i].Username == username)
            {
                _users.RemoveAt(i);
                return true;
            }
        }

        return false;
    }

    private void HandleRegister()
    {
        Console.WriteLine("\n=== 用户注册 ===");

        string username = GetValidUsername();
        if (string.IsNullOrEmpty(username))
        {
            Console.WriteLine("注册流程终止");
            return;
        }

        string password = GetValidPassword();
        if (string.IsNullOrEmpty(password))
        {
            Console.WriteLine("注册流程终止");
            return;
        }

        if (Register(username, password))
        {
            Console.WriteLine("注册成功！已返回主菜单");
        }
        else
        {
            Console.WriteLine("注册失败，用户名已存在");
        }
    }

    private void HandleLogin()
    {
        Console.WriteLine("\n=== 用户登录 ===");

        Console.Write("请输入用户名：");
        string username = Console.ReadLine()?.Trim();
        if (string.IsNullOrEmpty(username))
        {
            Console.WriteLine("用户名不可为空！登录失败");
            return;
        }

        Console.Write("请输入密码：");
        string password = Console.ReadLine()?.Trim();
        if (string.IsNullOrEmpty(password))
        {
            Console.WriteLine("密码不可为空！登录失败");
            return;
        }

        if (Login(username, password))
        {
            Console.WriteLine($"登录成功！欢迎回来，{username}！");
            Console.WriteLine("=== 系统首页 ===");
            Console.WriteLine("（模拟系统功能...）");
        }
        else
        {
            Console.WriteLine("登录失败：用户名或密码错误");
        }
    }

    private void HandleDeleteUser()
    {
        Console.WriteLine("\n=== 删除用户 ===");
        Console.Write("请输入要删除的用户名：");
        string username = Console.ReadLine()?.Trim();

        if (string.IsNullOrEmpty(username))
        {
            Console.WriteLine("用户名不可为空！删除失败");
            return;
        }

        if (DeleteUser(username))
        {
            Console.WriteLine("用户删除成功！");
        }
        else
        {
            Console.WriteLine("删除失败：用户名不存在");
        }
    }

    private string GetValidUsername()
    {
        while (true)
        {
            Console.Write("请输入用户名（3-15字符，仅含字母、数字、下划线）：");
            string username = Console.ReadLine()?.Trim();

            if (string.IsNullOrEmpty(username))
            {
                Console.WriteLine("用户名不可为空，请重新输入！");
                continue;
            }

            if (!Regex.IsMatch(username, @"^[a-zA-Z0-9_]{3,15}$"))
            {
                Console.WriteLine("用户名格式错误！需满足：");
                Console.WriteLine("1. 长度3-15个字符");
                Console.WriteLine("2. 仅包含字母、数字、下划线（_）");
                continue;
            }

            return username;
        }
    }

    private string GetValidPassword()
    {
        while (true)
        {
            Console.Write("请输入密码（6-20字符，含大小写字母和数字）：");
            string password = Console.ReadLine()?.Trim();

            if (string.IsNullOrEmpty(password))
            {
                Console.WriteLine("密码不可为空，请重新输入！");
                continue;
            }

            if (!Regex.IsMatch(password, @"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,20}$"))
            {
                Console.WriteLine("密码格式错误！需满足：");
                Console.WriteLine("1. 长度6-20个字符");
                Console.WriteLine("2. 包含至少1个大写字母、1个小写字母和1个数字");
                continue;
            }

            Console.Write("请确认密码：");
            string confirmPwd = Console.ReadLine()?.Trim();
            if (password != confirmPwd)
            {
                Console.WriteLine("两次输入的密码不一致，请重新输入！");
                continue;
            }

            return password;
        }
    }
}